package com.jm.service;

import com.jm.mapper.GoodsMapper;
import com.jm.model.Goods;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName GoodsServiceImpl
 * @Author chen.pian
 * @Date 2019/10/31 9:51
 **/
@Service(version = "1.0.0")
@Slf4j
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public void decGoods(Goods goods) {
        log.info("全局事务id ：" + RootContext.getXID());
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("commodity_code", goods.getCommodityCode());
        Goods goodsDB = goodsMapper.selectByMap(paramsMap).get(0);
        if (goodsDB.getCount() - goods.getCount() < 0) {
            throw new RuntimeException("库存不够");
        }
        int count = goodsMapper.decGoods(goods.getCommodityCode(), goods.getCount(), goodsDB.getCount());
        if (count <= 0) {
            throw new RuntimeException("更新库存失败");
        }
    }
}
